package com.qyhl.shop.shop.showcase.detail;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.tools.ScreenUtils;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.shop.ShopShowcaseBean;
import com.qyhl.webtv.commonlib.entity.shop.ShopShowcaseNormBean;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SHOP_SHOWCASE_DETAIL)
public class ShopShowcaseDetailActivity extends BaseActivity implements ShopShowcaseDetailContract.ShopShowcaseDetailView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.webView)
    WebView webView;
    @BindView(R2.id.norm_recycler)
    RecyclerView normRecycler;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.norm_title)
    TextView normTitle;

    @Autowired(name = "itemId")
    int itemId;

    private ShopShowcaseDetailPresenter mPresenter;

    private CommonAdapter<ShopShowcaseNormBean> commonAdapter;

    private List<ShopShowcaseNormBean> mDataList = new ArrayList<>();

    private ShopShowcaseBean mBean;


    @Override
    protected int getContentView() {
        return R.layout.shop_activity_showcase_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new ShopShowcaseDetailPresenter(this);

        initWebView();

        normRecycler.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));

        normRecycler.setAdapter(commonAdapter = new CommonAdapter<ShopShowcaseNormBean>(this, R.layout.shop_item_showcase_detail, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ShopShowcaseNormBean bean, int position) {
                holder.setText(R.id.norm, bean.getText());

                SpanUtils spUtils = new SpanUtils(ShopShowcaseDetailActivity.this);
                spUtils.append("¥")
                        .setSpans(new TextAppearanceSpan(ShopShowcaseDetailActivity.this, R.style.shop_showcase_price_three))
                        .append(StringUtils.splitDouble(bean.getPrice(), true))
                        .setSpans(new TextAppearanceSpan(ShopShowcaseDetailActivity.this, R.style.shop_showcase_price_four))
                        .append(StringUtils.splitDouble(bean.getPrice(), false))
                        .setSpans(new TextAppearanceSpan(ShopShowcaseDetailActivity.this, R.style.shop_showcase_price_three));
                TextView price = holder.getView(R.id.price);
                price.setText(spUtils.create());
            }
        });

        mPresenter.getDetail(itemId);
    }

    /**
     * 初始化webview
     */
    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(false);
        settings.setDefaultTextEncodingName("utf-8");
        settings.setDomStorageEnabled(true);
        settings.setBlockNetworkImage(false);//是否阻塞加载网络图片  协议http or https
        settings.setUseWideViewPort(false);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(itemId);
            }
        });
    }

    @Override
    public void setDetail(ShopShowcaseBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        mBean = bean;

        title.setText(bean.getItemName());

        String htmlString = getNewContent(bean.getItemDesc());
        webView.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);
        webView.setWebViewClient(mWebViewClient);

        if (bean.getNormList() != null && bean.getNormList().size() > 0) {
            normTitle.setVisibility(View.VISIBLE);

            mDataList.clear();
            mDataList.addAll(bean.getNormList());
            commonAdapter.notifyDataSetChanged();
        } else {
            normTitle.setVisibility(View.GONE);
        }

    }

    //webview中的图片自适应大小
    private String getNewContent(String htmlText) {
        Document document = Jsoup.parse(htmlText);
        Elements pElements = document.select("p:has(img)");
        for (Element pElement : pElements) {
            pElement.attr("style", "text-align:center");
            pElement.attr("max-width", String.valueOf(ScreenUtils.getScreenWidth(this) + "px"))
                    .attr("height", "auto");
        }
        Elements imgElements = document.select("img");
        for (Element imgElement : imgElements) {
            //重新设置宽高
            imgElement.attr("max-width", "100%")
                    .attr("height", "auto");
            imgElement.attr("style", "max-width:100%;height:auto");
        }
        return document.toString();
    }

    @Override
    public void setError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");

        loadMask.setErrorText(msg);
    }

    @OnClick({R2.id.back_btn, R2.id.share_btn})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.back_btn) {
            finish();
        } else if (viewId == R.id.share_btn) {
            if (mBean != null) {
                MShareBoard shareBoard = new MShareBoard(ShopShowcaseDetailActivity.this, mBean.getId() + "", mBean.getItemName(), mBean.getItemPic(), mBean.getItemDesc(), 41, false);
                shareBoard.showPopupWindow();
            }
        }
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return false;
            }

            return true;
        }


        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            //这个是一定要加上那个的,配合scrollView和WebView的height=wrap_content属性使用
            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            //重新测量
            webView.measure(w, h);

        }
    };
}
